package com.andy.drools.controller;

import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.andy.drools.model.Address;
import com.andy.drools.model.fact.AddressCheckResult;
import com.andy.drools.service.RuleConfigService;
import com.andy.drools.utils.DroolsUtils;

@RequestMapping("/test")
@Controller
public class TestDemoController {

	@Autowired
	private RuleConfigService ruleConfigService;

	@ResponseBody
	@RequestMapping("/address")
	public void test(int num) {
		Address address = new Address();
		address.setPostcode(generateRandom(num));
		String key = "front_key";
//		KieSession kieSession = DroolsUtils.getKieContainerMapByKey("front_key").newKieSession();
		KieSession kieSession = DroolsUtils.getKieContainer().newKieSession();

		AddressCheckResult result = new AddressCheckResult();
		kieSession.insert(address);
		kieSession.insert(result);
		int ruleFiredCount = kieSession.fireAllRules();
		kieSession.destroy();
		System.out.println("触发了" + ruleFiredCount + "条规则");

		if (result.isPostCodeResult()) {
			System.out.println("规则校验通过");
		}
	}

	/**
	 * 生成随机数
	 * 
	 * @param num
	 * @return
	 */
	public String generateRandom(int num) {
		String chars = "0123456789";
		StringBuffer number = new StringBuffer();
		for (int i = 0; i < num; i++) {
			int rand = (int) (Math.random() * 10);
			number = number.append(chars.charAt(rand));
		}
		return number.toString();
	}

	@ResponseBody
	@RequestMapping("/reload/{ruleType}")
	public String reloadRule(@PathVariable String ruleType) {
		DroolsUtils.reload(ruleType);
		return "更新规则成功";
	}

}
